package com.example.product.aspect;


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Aspect
@Component
public class LogAspect {

    @Pointcut("execution(* com.example.product.proxy.Calc.*(..))")
    public void pointCut() {

    }

    @Before("pointCut()")
    public void before(JoinPoint joinPoint) {
        System.out.println("log before");
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String name = signature.getName();
        Object[] args = joinPoint.getArgs();
        System.out.println("log before name:" + name + " args:" + Arrays.asList(args));
    }

    @After("execution(* com.example.product.proxy.Calc.*(..))")
    public void after(JoinPoint joinPoint) {
        System.out.println("log after");
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String name = signature.getName();
        System.out.println("log after name:" + name);
    }

    @AfterReturning(value = "pointCut()", returning = "object")
    public void afterReturn(JoinPoint joinPoint, Object object) {
        System.out.println("log after");
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String name = methodSignature.getMethod().getName();
        System.out.println("log after name:" + name + " return:" +object);
    }

    @AfterThrowing(value = "pointCut()", throwing = "ex")
    public void afterThrowing(JoinPoint joinPoint, Exception ex) {
        System.out.println("log afterThrowing");
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String name = methodSignature.getName();
        System.out.println("log afterThrowing name:" + name + " ex:" + ex);
    }
}
